<?php

//http://developers.facebook.com/docs/authentication/
require_once("kra_base.php");

class facebook extends kra_base {
    private $format = 'json';
    private $_user_fds = array(
	'uid' => 'id',
	'nickname' => 'name',
	'profile_url' => 'link',
	'thumbnail_url' => 'picture',
	'age' => 'birthday',
	'gender' => 'gender'
    );

    public function __construct($api_key = "", $api_secret = "", $app_id = 0) {
	$this->_api_key = $api_key;
	$this->_api_secret = $api_secret;
	$this->_app_id = $app_id;
	$this->_rest_url = 'https://graph.facebook.com';

	$this->get_paras();
    }

    public function __destruct() {
	
    }

    private function get_paras() {
	if ($_COOKIE['ssid']) {
	    $this->_user[uid] = $_COOKIE['ssid'];
	    $this->_session_key = $_COOKIE['skey'];
	}
    }

    protected function create_post_string($method, $params) {
	$params['access_token'] = $this->_session_key;
	$post_params = array();
	foreach ($params as $key => &$val) {
	    if (is_array($val))
		$val = implode(',', $val);
	    $post_params[] = $key . '=' . urlencode($val);
	}
	return implode('&', $post_params);
    }

    protected function parse_result($result) {
	$oresult = $result;
	$result = json_decode($result, true);
	if (!is_array($result)) {
	    $this->set_err(1004, print_r($oresult, 1));
	    return false;
	}
	return $result;
    }

    public function get_uid() {
	if ($this->_user[uid])
	    return $this->_user[uid];

	/* http://developers.facebook.com/docs/authentication/permissions */
	if (!$this->_app_id) {
	    echo "No appid found.";
	    exit();
	}

	$perms = array();
	if (!in_array("offline_access", $perms))
		$perms[] = "offline_access";
	if (!in_array("email", $perms))
		$perms[] = "email";
	if (!in_array("read_stream", $perms))
		$perms[] = "read_stream";
	if (!in_array("publish_stream", $perms))
		$perms[] = "publish_stream";

	$perms = implode(",", $perms);
	$callback_url = urlencode(SNS_AUTH_CALLBACK_URL);

	$code = $_REQUEST["code"];
	if (empty($code)) {
	    echo "<script>window.top.location.href='http://www.facebook.com/dialog/oauth?client_id={$this->_app_id}&redirect_uri={$callback_url}&scope={$perms}';</script>";
	    exit();
	}

	$resp = $this->httpRequest("https://graph.facebook.com/oauth/access_token", "client_id={$this->_app_id}&redirect_uri={$callback_url}&client_secret={$this->_api_secret}&code={$code}", "get");
	//$resp = self::httpcurl();
	//var_dump($resp);exit();
	if (!$resp) {
	    echo "<script>window.top.location.href='http://www.facebook.com/dialog/oauth?client_id={$this->_app_id}&redirect_uri={$callback_url}&scope={$perms}';</script>";
	    exit();
	}

	$params = null;
	parse_str($resp, $params);
	if (!$params) {
	    echo "<script>window.top.location.href='http://www.facebook.com/dialog/oauth?client_id={$this->_app_id}&redirect_uri={$callback_url}&scope={$perms}';</script>";
	    exit();
	}

	$this->_session_key = $params[access_token];
	$user = $this->me(array("uid", "profile_url", "nickname", "thumbnail_url", "gender", "age"));
	if (!$user || !$user[uid]) {
	    echo "<script>window.top.location.href='http://www.facebook.com/dialog/oauth?client_id={$this->_app_id}&redirect_uri={$callback_url}&scope={$perms}';</script>";
	    exit();
	}
	if ($this->_user[uid]) {
	    set_cookie("ssid", $this->_user[uid]);
	    set_cookie("skey", $this->_session_key);
	}
	return $this->_user[uid];
    }

    public function me($field = array()) {
	if ($this->_user)
	    return $this->_user;

	$field = $field ? $field : array_keys($this->_user_fds);

	$result = $this->post_request($method, array(), "get", "/me");

	if (!is_array($result) || $result[error]) {
	    $this->set_err(104, print_r($result, 1));
	    return false;
	}
	$this->set_err(0, "");
	$ret = array();
	foreach ($field as $fd) {
	    if (stripos($this->_user_fds[$fd], ".") !== false) {
		$tmp = explode(".", $this->_user_fds[$fd]);
		$p = "";
		if ($tmp) {
		    $p = $result;
		    foreach ($tmp as $t) {
			$p = $p[$t];
		    }
		}
		$ret[$fd] = $p;
	    } elseif ($fd == 'age') {
		$birth = $result[$this->_user_fds[$fd]] ? strtotime($result[$this->_user_fds[$fd]]) : "";
		if ($birth)
		    $ret[$fd] = floor((time() - $birth) / (365 * 86400));
		else
		    $ret[$fd] = 0;
	    }
	    else
		$ret[$fd] = $result[$this->_user_fds[$fd]] ? $result[$this->_user_fds[$fd]] : "";
	}
	if ($ret) {
	    $ret[thumbnail_url] = "http://graph.facebook.com/{$result[id]}/picture";
	    $ret[gender] = strtoupper($ret[gender]);
	}

	$this->_user = $ret;
	$this->_user[uid] = $result[id];
       
	return $ret;
        
    }

    public function friends($page = 1, $pagesize = 20, $hasapp = 0, $fullinfo = 0) {
	if (!$this->_user[uid]) {
	    $this->set_err(101, "Get paras err.");
	    return false;
	}
	$result = $this->post_request($method, array(), "get", "/me/friends");
	if (!is_array($result['data'])) {
	    $this->set_err(104, print_r($result, 1));
	    return false;
	}
	$this->set_err(0, "");

	if (!$result['data'])
	    return array();

	$ret = array();
	if ($fullinfo) {
	    foreach ($result['data'] as $user) {
		$user = (array) $user;
		$uidk = $this->_user_fds[uid];
		$uid = $user[$uidk];
		if (!$uid)
		    continue;

		$row[uid] = $uid;
		$row[nickname] = $user[name];
		$row[thumbnail_url] = "http://graph.facebook.com/{$uid}/picture";

		$ret[$row[uid]] = $row;
	    }
	}
	else {
	    foreach ($result['data'] as $user) {
		$user = (array) $user;
		$uidk = $this->_user_fds[uid];
		$uid = $user[$uidk];
		if (!$uid)
		    continue;

		$ret[$uid] = $uid;
	    }
	}
	return $ret;
    }

    public function request_permissions($callback_url = "", $perms = array()) {
	
    }

    public function counter($count = 0, $uid = 0) {
	$ourl = $this->_rest_url;
	$this->_rest_url = "https://api.facebook.com/method/dashboard.setCount";
	$uid = $uid ? $uid : $this->_user[uid];

	$res = $this->post_request("", array(
		    "count" => $count,
		    "uid" => $uid
			), "get", "", 0);
	$this->_rest_url = $ourl;

	return $res;
    }

    public function photo($filepath = "", $title = "") {
	if (!$filepath || !file_exists($filepath)) {
	    $this->set_err(101, "No file path or file not exists.");
	    return false;
	}

	$params = array("source" => '@' . $filepath, "message" => $title, "access_token" => $this->_session_key);

	$result = $this->post_request($method, $params, "post", "/me/photos", 1, 1);
	if (!is_array($result) || $result[error]) {
	    $this->set_err(104, print_r($result, 1));
	    return false;
	}

	return $result;
    }

}

?>
